import {
  Body,
  Controller,
  Inject,
  Post,
  HttpException,
  HttpStatus,
} from '@nestjs/common';
import { AdminUserService } from './AdminUser.service';
import AdminLoginDto from '@/dto/AdminLogin.dto';
import { ConfigService } from '@nestjs/config';
import { JwtService } from '@nestjs/jwt';

@Controller('admin')
export class AdminUserController {
  @Inject(AdminUserService)
  private readonly adminUserService: AdminUserService;

  @Inject(ConfigService)
  private readonly configService: ConfigService;

  @Inject(JwtService)
  private readonly jwtService: JwtService;

  @Post('login')
  async login(@Body() userInfo: AdminLoginDto) {
    const user = await this.adminUserService.login(userInfo);
    if (!user) {
      throw new HttpException('用户名或密码错误', HttpStatus.BAD_REQUEST);
    }
    const accessToken = this.jwtService.sign(
      {
        userId: user.id,
        isAdmin: true,
      },
      {
        expiresIn: this.configService.get('jwt.access_token_expires') || '30m',
      },
    );
    return accessToken;
  }
}
